#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/10 15:05
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : configEmail.py
from common.readConfig import ReadConfig
from ProjectPath import projectPath
import os
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from common.cryptoTool import RsaCrypto
from common.setConfig import SetConfig

htmlConfig = ReadConfig()

def get_case_result(reportFileName):
    '''获取测试用例报告'''
    htmlContent = ''
    resportHTMLFile = os.path.join(projectPath,'resultreport',reportFileName)
    with open(resportHTMLFile,'r',encoding='utf-8') as f:
        htmlContent = f.read()
    return htmlContent,resportHTMLFile

def getMailPasswd():
    rsa = RsaCrypto()
    mailPwd_encrypt = rsa.encrypt('12345678')['message']
    SetConfig().setEmailConfig('mail_pass',mailPwd_encrypt)
    mail_passwd = rsa.decrypt(mailPwd_encrypt)['message']
    return mail_passwd

def send_email(reportFileName='接口自动化测试报告.html'):
    subject = htmlConfig.get_email('subject')
    mail_host = htmlConfig.get_email('mail_host')
    mail_user = htmlConfig.get_email('mail_user')
    mail_passwd = getMailPasswd()
    sender = htmlConfig.get_email('sender')
    receivers = str(htmlConfig.get_email('receivers')).split(',') #获取配置文件中收件人，并转换成列表
    htmlContent,resportHTMLFile = get_case_result(reportFileName) #获取html文件内容
    message = MIMEMultipart()  #创建一个带附件的实例

    #定义邮件标头
    message['From'] = Header('李中华',charset='utf-8')
    message['To'] = ','.join(receivers)
    message['Subject'] = Header(subject,'utf-8')

    # 邮件正文内容
    mailContent = MIMEText(htmlContent, 'html', 'utf-8')

    print(resportHTMLFile)

    #构建附件
    att = MIMEText(open(resportHTMLFile,'rb').read(),'base64','utf-8')
    att['Content-Type'] = 'application/octet-stream'
    #添加附件
    att.add_header('Content-Disposition','attachment',filename=Header(reportFileName,'utf-8').encode())

    # 添加邮件正文和附件到邮件实例中
    message.attach(mailContent)
    message.attach(att)

    try:
        smtpObj = smtplib.SMTP(mail_host, 587)
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(mail_user, mail_passwd)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print('邮件发送成功')
    except smtplib.SMTPException as e:
        print(e)


if __name__ == '__main__':
    # print(get_case_result())
    # send_email('接口自动化测试报告.html')
    print(getMailPasswd())


